import os
import json
import base64
import hashlib
import hmac
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
import ssl

from flask import Flask, render_template, request, redirect, url_for, send_from_directory, flash
import requests
import websocket
from wsgiref.handlers import format_date_time
from PIL import Image
import uuid
import threading

# ------------------------ 配置 ------------------------ #

APPId = "9952d66b"  
APISecret = "MTVkM2ExYTlhOTg2YTkzOWQxYWZjNWI2"  
APIKey = "8daf236addd09590607db513a87db1ce"  

# 创建 Flask 应用
app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 替换为您的密钥

# 设置上传和音频存储路径
UPLOAD_FOLDER = 'static/uploads'
AUDIO_FOLDER = 'static/audios'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(AUDIO_FOLDER, exist_ok=True)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['AUDIO_FOLDER'] = AUDIO_FOLDER

# ------------------------ 辅助类 ------------------------ #

class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg

class Url:
    def __init__(self, host, path, schema):
        self.host = host
        self.path = path
        self.schema = schema

# ------------------------ 辅助函数 ------------------------ #

def sha256base64(data):
    sha256 = hashlib.sha256()
    sha256.update(data)
    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')
    return digest

def parse_url(request_url):
    stidx = request_url.index("://")
    host = request_url[stidx + 3:]
    schema = request_url[:stidx + 3]
    edidx = host.index("/")
    if edidx <= 0:
        raise AssembleHeaderException("无效的请求 URL:" + request_url)
    path = host[edidx:]
    host = host[:edidx]
    u = Url(host, path, schema)
    return u

def assemble_ws_auth_url(request_url, method="POST", api_key="", api_secret=""):
    u = parse_url(request_url)
    host = u.host
    path = u.path
    now = datetime.now()
    date = format_date_time(mktime(now.timetuple()))
    signature_origin = f"host: {host}\ndate: {date}\n{method} {path} HTTP/1.1"
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha}"'
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    values = {
        "host": host,
        "date": date,
        "authorization": authorization
    }
    return request_url + "?" + urlencode(values)

# ------------------------ OCR 功能 ------------------------ #

def perform_ocr(image_path):
    try:
        with open(image_path, "rb") as f:
            imageBytes = f.read()
        
        url = 'https://api.xf-yun.com/v1/private/sf8e6aca1'
        
        body = {
            "header": {
                "app_id": APPId,
                "status": 3
            },
            "parameter": {
                "sf8e6aca1": {
                    "category": "ch_en_public_cloud",
                    "result": {
                        "encoding": "utf8",
                        "compress": "raw",
                        "format": "json"
                    }
                }
            },
            "payload": {
                "sf8e6aca1_data_1": {
                    "encoding": "jpg",
                    "image": base64.b64encode(imageBytes).decode('utf-8'),
                    "status": 3
                }
            }
        }
        
        request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
        
        headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
        response = requests.post(request_url, data=json.dumps(body), headers=headers)
        
        if response.status_code != 200:
            raise Exception(f"HTTP 错误: {response.status_code}")
        
        tempResult = response.json()
        if 'payload' not in tempResult or 'result' not in tempResult['payload']:
            raise Exception(f"无效的响应: {response.text}")
        
        # Base64 解码后的内容
        decoded_text = base64.b64decode(tempResult['payload']['result']['text']).decode()
        
        # 解析 JSON
        ocr_result = json.loads(decoded_text)
        
        # 提取 'content' 字段
        extracted_text = ""
        for page in ocr_result.get("pages", []):
            for line in page.get("lines", []):
                for word in line.get("words", []):
                    extracted_text += word.get("content", "")
        
        return extracted_text
    except Exception as e:
        raise e

# ------------------------ TTS 功能 ------------------------ #

STATUS_FIRST_FRAME = 0  # 第一帧的标识
STATUS_CONTINUE_FRAME = 1  # 中间帧标识
STATUS_LAST_FRAME = 2  # 最后一帧的标识

class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret, Text):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.Text = Text

        # 公共参数(common)
        self.CommonArgs = {"app_id": self.APPID}
        # 业务参数(business)，更多个性化参数可在官网查看
        # 将 "aue" 从 "raw" 改为 "lame" 以获取 MP3 格式的音频
        self.BusinessArgs = {"aue": "lame", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
        self.Data = {"status": 2, "text": base64.b64encode(self.Text.encode('utf-8')).decode("UTF8")}

    # 生成 URL
    def create_url(self):
        url = 'wss://tts-api.xfyun.cn/v2/tts'
        # 生成 RFC1123 格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + "tts-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
        # 进行 hmac-sha256 加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha}"'
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": "tts-api.xfyun.cn"
        }
        # 拼接鉴权参数，生成 URL
        url = url + '?' + urlencode(v)
        return url

def tts(text, output_audio_path, progress_callback=None):
    def on_message(ws, message):
        try:
            message = json.loads(message)
            code = message["code"]
            sid = message["sid"]
            if code != 0:
                errMsg = message.get("message", "")
                if progress_callback:
                    progress_callback(f"sid:{sid} 调用错误:{errMsg} 代码:{code}")
                ws.close()
            else:
                if 'data' in message:
                    audio = message["data"].get("audio", "")
                    status = message["data"].get("status", 0)
                    if audio:
                        with open(output_audio_path, 'ab') as f:
                            f.write(base64.b64decode(audio))
                    if status == 2:
                        if progress_callback:
                            progress_callback("TTS 完成。")
                        ws.close()
        except Exception as e:
            if progress_callback:
                progress_callback(f"接收消息但解析异常: {e}")

    def on_error(ws, error):
        if progress_callback:
            progress_callback(f"WebSocket 错误: {error}")

    def on_close(ws):
        if progress_callback:
            progress_callback("WebSocket 已关闭。")

    def on_open(ws):
        def run():
            d = {
                "common": wsParam.CommonArgs,
                "business": wsParam.BusinessArgs,
                "data": wsParam.Data,
            }
            d = json.dumps(d)
            if progress_callback:
                progress_callback("开始发送文本数据进行 TTS...")
            ws.send(d)
        threading.Thread(target=run).start()

    wsParam = Ws_Param(APPId, APIKey, APISecret, text)
    wsUrl = wsParam.create_url()
    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

# ------------------------ Flask 路由 ------------------------ #

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # 检查是否有文件上传
        if 'image' not in request.files:
            flash('没有上传文件')
            return redirect(request.url)
        file = request.files['image']
        if file.filename == '':
            flash('没有选择文件')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            # 生成唯一文件名
            filename = secure_filename(file.filename)
            unique_filename = f"{uuid.uuid4().hex}_{filename}"
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
            file.save(file_path)

            try:
                # 执行 OCR
                recognized_text = perform_ocr(file_path)
            except Exception as e:
                flash(f"OCR 失败: {e}")
                return redirect(request.url)

            if not recognized_text:
                flash("未识别到文本")
                return redirect(request.url)

            # 生成音频文件名
            audio_filename = f"{uuid.uuid4().hex}.mp3"
            audio_path = os.path.join(app.config['AUDIO_FOLDER'], audio_filename)

            # 执行 TTS
            try:
                # TTS 可能需要一定时间，建议在实际应用中使用异步任务
                tts(recognized_text, audio_path)
            except Exception as e:
                flash(f"TTS 失败: {e}")
                return redirect(request.url)

            # 返回结果页面
            return render_template('result.html',
                                   image_url=url_for('uploaded_file', filename=unique_filename),
                                   recognized_text=recognized_text,
                                   audio_url=url_for('audio_file', filename=audio_filename))
    return render_template('index.html')

def allowed_file(filename):
    allowed_extensions = {'jpg', 'jpeg', 'png', 'bmp', 'gif'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions

from werkzeug.utils import secure_filename

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/audios/<filename>')
def audio_file(filename):
    return send_from_directory(app.config['AUDIO_FOLDER'], filename)

# ------------------------ 运行应用 ------------------------ #

if __name__ == "__main__":
    app.run(debug=True)
